package org.sjs.dreamfly.biz.history

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.sjs.dreamfly.common.base.BaseViewModel
import org.sjs.dreamfly.common.util.PhemonUtils
import org.sjs.dreamfly.data.AppDataBase
import org.sjs.dreamfly.data.HistoryItemDao
import org.sjs.dreamfly.model.HistoryItem
import org.sjs.dreamfly.model.ResourceType

class HistoryViewModel : BaseViewModel() {
    private val historyList = mutableListOf<HistoryItem>()
    private val historyDao = AppDataBase.getDatabase().historyDao()
    private val movieDao = AppDataBase.getDatabase().movieDao()

    fun getHistoryList(): List<HistoryItem> {
        return historyList
    }

    suspend fun loadHistory(): List<HistoryItem> = withContext(Dispatchers.IO) {
        val result = historyDao.loadAll()
        historyList.clear()
        historyList.addAll(result)
        result.forEach {
            if (it.resourceType == ResourceType.MOVIE) {
                movieDao.query(it.resourceId).firstOrNull()?.let { movie->
                    it.movieInfo = movie
                }
            }
        }
        return@withContext historyList
    }
}